#!/usr/bin/env python
# -*- coding: utf-8 -*-

# generate-plugin.py - pluma plugin skeletton generator
# This file is part of pluma
#
# Copyright (C) 2006 - Steve Frécinaux
#
# pluma is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# pluma is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pluma; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA  02110-1301  USA

import re
import os
import sys
import getopt
from datetime import date
import preprocessor

# Default values of command line options
options = {
    'language'          : 'c',
    'description'       : 'Type here a short description of your plugin',
    'author'            : os.getenv('USERNAME'),
    'email'             : os.getenv('LOGNAME') + '@email.com',
    'standalone'        : False,
    'with-side-pane'    : False,
    'with-bottom-pane'  : False,
    'with-menu'         : False,
    'with-config-dlg'   : False
}

USAGE = """Usage:
   %s [OPTIONS...] pluginname
""" % os.path.basename(sys.argv[0])
HELP = USAGE + """
generate skeleton source tree for a new pluma plugin.

Options:
  --author              Set the author name
  --email               Set the author email
  --description         Set the description you want for your new plugin
  --standalone          Is this plugin intended to be distributed as a
                        standalone package ? (N/A)
  --language / -l       Set the language (C) [default: %(language)s]
  --with-$feature       Enable $feature
  --without-$feature    Disable $feature
  --help / -h           Show this message and exits

Features:
  config-dlg            Plugin configuration dialog
  menu                  Plugin menu entries
  side-pane             Side pane item (N/A)
  bottom-pane           Bottom pane item (N/A)
""" % options

TEMPLATE_DIR = os.path.join(os.path.dirname(sys.argv[0]), "plugin_template")

# Parsing command line options
try:
    opts, args = getopt.getopt(sys.argv[1:],
                               'l:h',
                               ['language=',
                                'description=',
                                'author=',
                                'email=',
                                'standalone',
                                'with-menu'         , 'without-menu',
                                'with-side-pane'    , 'without-side-pane',
                                'with-bottom-pane'  , 'without-bottom-pane',
                                'with-config-dlg'   , 'without-config-dlg',
                                'help'])
except getopt.error, exc:
    print >>sys.stderr, '%s: %s' % (sys.argv[0], str(exc))
    print >>sys.stderr, USAGE
    sys.exit(1)

for opt, arg in opts:
    if opt in ('-h', '--help'):
        print >>sys.stderr, HELP
        sys.exit(0)

    elif opt in ('--description', '--author', '--email'):
        options[opt[2:]] = arg

    elif opt in ('-l', '--language'):
        options['language'] = arg.lower()

    elif opt == '--standalone':
        options['standalone'] = True

    elif opt[0:7] == '--with-':
        options['with-' + opt[7:]] = True

    elif opt[0:10] == '--without-':
        options['with-' + opt[10:]] = False

# What's the new plugin name ?
if len(args) < 1:
    print >>sys.stderr, USAGE
    sys.exit(1)

plugin_name = args[0]
plugin_id = re.sub('[^a-z0-9_]', '', plugin_name.lower().replace(' ', '_'))
plugin_module = plugin_id.replace('_', '-')

directives = {
    'PLUGIN_NAME'       : plugin_name,
    'PLUGIN_MODULE'     : plugin_module,
    'PLUGIN_ID'         : plugin_id,
    'AUTHOR_FULLNAME'   : options['author'],
    'AUTHOR_EMAIL'      : options['email'],
    'DATE_YEAR'         : date.today().year,
    'DESCRIPTION'       : options['description'],
}

# Files to be generated by the preprocessor, in the form "template : outfile"
output_files = {
    'Makefile.am': '%s/Makefile.am' % plugin_module,
    'pluma-plugin.desktop.in': '%s/%s.pluma-plugin.desktop.in' % (plugin_module, plugin_module)
}

if options['language'] == 'c':
    output_files['pluma-plugin.c'] = '%s/%s-plugin.c' % (plugin_module, plugin_module)
    output_files['pluma-plugin.h'] = '%s/%s-plugin.h' % (plugin_module, plugin_module)
else:
    print >>sys.stderr, 'Value of --language should be C'
    print >>sys.stderr, USAGE
    sys.exit(1)

if options['standalone']:
    output_files['configure.ac'] = 'configure.ac'

if options['with-side-pane']:
    directives['WITH_SIDE_PANE'] = True

if options['with-bottom-pane']:
    directives['WITH_BOTTOM_PANE'] = True

if options['with-menu']:
    directives['WITH_MENU'] = True

if options['with-config-dlg']:
    directives['WITH_CONFIGURE_DIALOG'] = True


# Generate the plugin base
for infile, outfile in output_files.iteritems():
    print 'Processing %s\n' \
          '      into %s...' % (infile, outfile)

    infile = os.path.join(TEMPLATE_DIR, infile)
    outfile = os.path.join(os.getcwd(), outfile)

    if not os.path.isfile(infile):
        print >>sys.stderr, 'Input file does not exist : %s.' % os.path.basename(infile)
        continue

    # Make sure the destination directory exists
    if not os.path.isdir(os.path.split(outfile)[0]):
        os.makedirs(os.path.split(outfile)[0])

    # Variables relative to the generated file
    directives['DIRNAME'], directives['FILENAME'] = os.path.split(outfile)

    # Generate the file
    preprocessor.process(infile, outfile, directives.copy())

print 'Done.'

# ex:ts=4:et:
